<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>拼多多在线商城</title>
    <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <link rel="stylesheet" href="css/timeClock.css">
    <link rel="stylesheet" href="./css/index.css">
    <link rel="stylesheet" href="./css/jieshao.css">
    <style>
        /* 示例：使用 Flex 布局保证列表内的商品盒子排列整齐 */
        .nei_pohot ul {
            display: flex;
            flex-wrap: wrap;
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .phone_tu {
            width: 200px;
            margin: 10px;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            border: 1px solid #ddd;
            padding: 10px;
        }
        .phone_tu img {
            max-width: 100%;
            height: auto;
        }
        /* 针对类别容器的样式 */
        .category-container {
            margin-bottom: 30px;
        }
        .box_tit.w {
            background-color: #f5f5f5;
            padding: 10px;
        }
    </style>
</head>
<body>
<%
    String defaultUrl = "https://tse1-mm.cn.bing.net/th/id/OIP-C.j57souiFOvYA0LUiw-2BkAHaHa?rs=1&pid=ImgDetMain";
    HttpSession session1 = request.getSession();
    String userType = (String) session1.getAttribute("userType");
    String username = null;
    String avatarUrl = null;
    if (userType != null) {
        if ("admin".equals(userType)) {
            username = (String) session1.getAttribute("adminUsername");
            avatarUrl = (String) session1.getAttribute("adminAvatarUrl");
        } else {
            username = (String) session1.getAttribute("username");
            avatarUrl = (String) session1.getAttribute("userAvatarUrl");
        }
    }
%>
<header>
    <ul>
        <li><a href="./index.jsp">首页</a></li>
        <li><a href="./aboutUs.jsp">关于我们</a></li>
        <li><a href="user/owner.jsp">个人主页</a></li>
        <li><a href="ai.jsp">智能问答</a></li>
        <% if (userType == null) { %>
        <li><a href="./login.jsp">登录</a></li>
        <li><a href="managerLogin.jsp" class="admin-link">管理员登录</a></li>
        <% } else { %>
        <li><span>欢迎，<%= username %></span></li>
        <li><a href="#" onclick="logout()">退出登录</a></li>
        <% } %>
        <li>
            <% if (userType != null) { %>
            <img src="<%= (avatarUrl != null && !avatarUrl.isEmpty()) ? avatarUrl : defaultUrl %>"
                 alt="头像"
                 id="userAvatar"
                 style="width: 50px; height: 50px; border-radius: 50%;"
                 onerror="this.src='<%= defaultUrl %>'"
                 onclick="goToInfo()">
            <% } %>
        </li>
        <li><button onclick="viewCart()" class="shopCar">查看购物车</button></li>
    </ul>
</header>

<div class="time"></div>

<div class="container">
    <div class="imgs">
        <a href="#" class="active">
            <img src="./images/lunboimage/1.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/2.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/3.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/4.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/5.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/6.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/7.jpg" alt="">
        </a>
        <a href="#">
            <img src="./images/lunboimage/8.jpg" alt="">
        </a>
    </div>
    <div class="shades">
        <div class="left"></div>
        <div class="top"></div>
        <div class="right"></div>
        <div class="bottom"></div>
    </div>
    <div class="titles">
        <a href="#" class="active">
            <div class="title">头条</div>
            <div class="title2">大降价！小米12价格有所下降</div>
        </a>
        <a href="#">
            <div class="title">双十一特惠</div>
            <div class="title2">各种电脑电器价格大幅下降</div>
        </a>
        <a href="#">
            <div class="title">好消息</div>
            <div class="title2">xmage手机价格回暖</div>
        </a>
        <a href="#">
            <div class="title">了不起！酷睿13</div>
            <div class="title2">轻薄专区，燃爆双十一！！！</div>
        </a>
        <a href="#">
            <div class="title">中国风卫衣上线</div>
            <div class="title2">情侣双色衣服供您挑选！</div>
        </a>
        <a href="#">
            <div class="title">气动科技系列上新</div>
            <div class="title2">蓬松衣，全新保暖！！！</div>
        </a>
        <a href="#">
            <div class="title">李宁上线</div>
            <div class="title2">全新的柔感上线商城</div>
        </a>
        <a href="#">
            <div class="title">星际巡航</div>
            <div class="title2">中国国家队乒乓球队比赛衣服</div>
        </a>
    </div>
</div>

<div class="shop">
    <div class="lunbo">
        <span class="right" id="right"></span>
        <span class="left" id="left"></span>
        <div id="lunbo">
            <div>
                <a href="#"><img src="images/pingban5.png" alt=""></a>
            </div>
            <div>
                <a href="#"><img src="images/pingban5.png" alt=""></a>
            </div>
            <div>
                <a href="#"><img src="images/450ebe4e2420eba7064b6ce08b2fc503.jpg" alt=""></a>
            </div>
            <div>
                <a href="#"><img src="images/3e34ddd6b7bcbfb90ed09e871d291593.png" alt=""></a>
            </div>
            <div>
                <a href="#"><img src="images/f89261d8655d76f2ab2340e4a3738678.jpg" alt=""></a>
            </div>
        </div>
    </div>
    <!-- 商品数据将通过 AJAX 动态加载 -->
    <div id="shopItems"></div>
</div>

<div class="nav">
    <ul>
        <li class="current">手机</li>
        <li>电脑</li>
        <li>家居</li>
        <li>服饰</li>
        <div class="back">返回顶部</div>
    </ul>
</div>

<div class="footer">
    <div class="translate">
        <div class="footer-links">
            <h5>购物指南</h5>
            <ul>
                <li><a href="#">购物流程</a></li>
                <li><a href="#">会员介绍</a></li>
                <li><a href="#">生活旅行</a></li>
                <li><a href="#">常见问题</a></li>
                <li><a href="#">联系客服</a></li>
            </ul>
        </div>
        <div class="footer-links">
            <h5>支付方式</h5>
            <ul>
                <li><a href="#">信用卡</a></li>
                <li><a href="#">货到付款</a></li>
                <li><a href="#">在线付款</a></li>
                <li><a href="#">分期付款</a></li>
            </ul>
        </div>
        <div class="footer-links">
            <h5>售后服务</h5>
            <ul>
                <li><a href="#">售后政策</a></li>
                <li><a href="#">退款说明</a></li>
                <li><a href="#">返修/退换货</a></li>
            </ul>
        </div>
        <div class="footer-links">
            <h5>帮助中心</h5>
            <ul>
                <li><a href="#">账户管理</a></li>
                <li><a href="#">自助服务</a></li>
                <li><a href="#">订单操作</a></li>
                <li><a href="#">服务网点</a></li>
                <li><a href="#">授权体验店/专区</a></li>
            </ul>
        </div>
        <div class="footer-links">
            <h5>关于我们</h5>
            <ul>
                <li><a href="#">新浪微博</a></li>
                <li><a href="#">官方微信</a></li>
                <li><a href="#">联系我们</a></li>
                <li><a href="#">加入我们</a></li>
                <li><a href="#">公益基金会</a></li>
            </ul>
        </div>
    </div>
</div>

<script src="./js/index.js"></script>
<script src="./js/timeClock.js"></script>
<script>
    function goToInfo() {
        <% if ("admin".equals(userType)) { %>
        window.location.href = 'admin/adminInfo.jsp';
        <% } else if (userType != null) { %>
        window.location.href = 'user/owner.jsp';
        <% } %>
    }
    function logout() {
        const userType = '<%= userType %>';
        const servletUrl = userType === 'admin' ? 'adminInfoServlet' : 'userLogoutServlet';
        fetch(servletUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=logout'
        })
            .then(response => { if (response.ok) { window.location.href = './index.jsp'; } })
            .catch(error => { console.error('Error:', error); alert('退出登录失败，请重试'); });
    }
    function viewCart() {
        <% if (userType == null) { %>
        alert('请先登录');
        window.location.href = './login.jsp';
        <% } else { %>
        window.location.href = 'user/cart.jsp';
        <% } %>
    }
    function addToCart(productName, price) {
        <% if ("admin".equals(userType)) { %>
        alert('管理员账号无法购物，请使用普通用户账号');
        return;
        <% } %>
        <% if (userType == null) { %>
        alert('请先登录');
        window.location.href = './login.jsp';
        return;
        <% } %>
        const formData = new FormData();
        formData.append('productName', productName);
        formData.append('price', price);
        fetch('cartServlet', { method: 'POST', body: formData })
            .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.json(); })
            .then(result => {
                if (result.status === 'success') {
                    alert('添加到购物车成功！');
                } else {
                    alert('添加失败：' + result.message);
                }
            })
            .catch(error => { console.error('Error:', error); alert('添加失败，请重试'); });
    }
    function placeOrder(productName, price) {
        <% if (userType == null) { %>
        alert('请先登录');
        window.location.href = './login.jsp';
        return;
        <% } %>
        const formData = new FormData();
        formData.append('productName', productName);
        formData.append('price', price);
        fetch('orderServlet', { method: 'POST', body: formData })
            .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.json(); })
            .then(result => {
                if (result.status === 'success') {
                    alert('下单成功！');
                } else {
                    alert('下单失败：' + result.message);
                }
            })
            .catch(error => { console.error('Error:', error); alert('下单失败，请重试'); });
    }
    $(document).ready(function(){
        $.ajax({
            url: 'getShopItem',
            method: 'GET',
            dataType: 'json',
            success: function(data) { renderProducts(data); },
            error: function(xhr, status, error) { console.error("获取产品数据失败：", error); }
        });
    });
    function renderProducts(data) {
        var container = $("#shopItems");
        container.empty();
        $.each(data, function(category, products) {
            // 将每个类别的标题和商品列表放入一个统一的容器中
            var categoryContainer = $('<div class="category-container"></div>');
            var categoryDiv = $('<div class="box_tit w"></div>');
            categoryDiv.append('<h2 class="title">' + category + '</h2>');

            var listDiv = $('<div class="nei_pohot"><ul></ul></div>');
            var ul = listDiv.find("ul");

            $.each(products, function(index, product) {
                var li = $('<li class="phone_tu"></li>');
                var a = $('<a href="#"></a>');
                var ph = $('<div class="ph"><img src="' + product.imageUrl + '" alt=""></div>');
                var na = $('<div class="na">' + product.name + '</div>');
                var price = $('<p>￥' + product.price + '</p>');
                var cartBtn = $('<button style="margin-left: 70px;" onclick="addToCart(\'' + product.name + '\', \'' + product.price + '\')">添加到购物车</button>');
                var orderBtn = $('<button style="margin-left: 10px;" onclick="placeOrder(\'' + product.name + '\', \'' + product.price + '\')">立即下单</button>');
                a.append(ph).append(na).append(price).append(cartBtn).append(orderBtn);
                li.append(a);
                ul.append(li);
            });

            categoryContainer.append(categoryDiv).append(listDiv);
            container.append(categoryContainer);
        });
    }
</script>
</body>
</html>
